﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waker.APIs.ADS;
using Waker.Common;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using System.Threading;
using DevExpress.XtraBars;
using Waker.Entitys;

namespace Waker.Devices
{
    public partial class FormDevice : Base.FormBaseToolBar
    {
        public FormDevice()
        {
            InitializeComponent();

            //var temp = new LinkPersistInfo(barSubItem1);
            //temp.BeginGroup = true;
            //this.bar1.LinksPersistInfo.Insert(4, temp); 
        }
        ADSHalDataStruct.ADS_CommunicationParameter m_comm = new ADSHalDataStruct.ADS_CommunicationParameter();
        private void FormDevice_Load(object sender, EventArgs e)
        {
            this.gridView1.RowClick += new DevExpress.XtraGrid.Views.Grid.RowClickEventHandler(gridView1_RowClick);
            FormRefresh();
        }
        public override void FormRefresh()
        {
            var ds = new BAL.BAL_Device().GetDeviceAll();

            if (ds != null && ds.Tables.Count > 2)
            {
                ds.Relations.Add("reLSubDevice", ds.Tables[0].Columns["Device_ID"], ds.Tables[1].Columns["Device_ID"]);
                //ds.Relations.Add("reIO", ds.Tables[1].Columns["LSubDevice_ID"], ds.Tables[2].Columns["LSubDevice_ID"]);
                //this.gridControl1.LevelTree.LevelTemplate = this.gridView1;
                //this.gridControl1.LevelTree.RelationName = "reLSubDevice";
                //gridView1.ViewCaption = "门禁设备";
                this.gridControl1.DataSource = ds.Tables[0];
                this.gridView1.ExpandMasterRow(0);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //// 连接
                    //m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
                    //m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
                    //m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));
                    ////Session._ADS_Comadapter.type = (byte)ADSHalConstant.ADS_COMAdapterType.ADS_ADT_TCP;
                    //int iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref m_comm);
                    //dr["Reserver_Str"] = iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS ? "在线" : "离线";
                    dr["Reserver_Str"] = "离线";
                }
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    dr["Reserver_Str"] = "离线";
                }
                timer1.Enabled = true;
                timer1.Interval = 1000;
            }
        }
        protected override void FormAdd()
        {
            var f = new FormDeviceEdit(string.Empty);
            var res = f.ShowDialog();
            if (res == DialogResult.OK)
                FormRefresh();
        }
        protected override void FormEdit()
        {
            if (gridView1.FocusedRowHandle < 0)
                return;
            var dr = gridView1.GetFocusedDataRow();
            if (dr == null)
                return;
            var f = new FormDeviceEdit(dr["Device_ID"].ToString());
            var res = f.ShowDialog();
            if (res == DialogResult.OK)
            {
                var main = this.MdiParent as FormMain;
                if (main != null)
                    main.InitADS();
                FormRefresh();
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks > 1)
            {
                //if (gridControl1.FocusedView.Name == "gridView1")
                FormEdit();
                //else
                //{

                //}
            }
        }
        protected override void FormDelete()
        {
            if (gridView1.FocusedRowHandle < 0)
                return;
            var dr = gridView1.GetFocusedDataRow();
            if (dr == null || dr["Device_ID"] == DBNull.Value || string.IsNullOrEmpty(dr["Device_ID"].ToString()))
                return;
            if (UI.ShowWarningOKCancel(string.Format("确定删除门禁设备[{0}]吗?", dr["Device_Name"]), "删除提示") != DialogResult.OK)
                return;
            var isOK = new BAL.BAL_Device().DeleteDevice((dr["Device_ID"]).ToString());
            if (isOK)
            {
                UI.ShowInfo("删除成功");
                FormRefresh();
            }
            else
            {
                UI.ShowError("删除失败");
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                var dt = this.gridControl1.DataSource as DataTable;
                if (dt == null || dt.Rows.Count < 1)
                {
                    timer1.Enabled = false;
                    return;
                }
                StartWaiting();
                foreach (DataRow dr in dt.Rows)
                {
                    //先ping ip 如果存在在连接
                    if (!IPHelper.TestNetConnected(dr["ComAdapter_Addr"].ToString(), 1, 3))
                    {
                        continue;
                    }
                    //// 连接
                    m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
                    m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
                    m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));
                    //Session._ADS_Comadapter.type = (byte)ADSHalConstant.ADS_COMAdapterType.ADS_ADT_TCP;
                    int iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref m_comm);
                    var isok = iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS;
                    dr["Reserver_Str"] = isok ? "在线" : "离线";
                    if (isok)
                    {
                        var drs = dr.GetChildRows("reLSubDevice");
                        if (drs.Length < 1)
                            continue;
                        foreach (DataRow drSub in drs)
                        {
                            ADSHalDataStruct.ADS_LogicSubDeviceAddress subAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress();
                            subAddress.physicalSubDevAddr = 0;
                            subAddress.logicSubDevNumber = Convert.ToByte(drSub["Physics_ID"]);

                            if (subAddress.logicSubDevNumber != 0)
                            {
                                uint uOnLine = 0;
                                uint uState = 0;
                                int res = ADSHalAPI.ADS_GetLogicSubDeviceState(ref Session._ADS_Comadapter, ref m_comm, ref subAddress, ref uOnLine, ref uState);
                                //ADSHelp.PromptResult(res, true);

                                if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                {
                                    if (uOnLine == 0)
                                    {
                                        drSub["Reserver_Str"] = "离线";
                                    }
                                    else
                                    {
                                        drSub["Reserver_Str"] = "在线-" + ((uState == 1) ? "门开" : "门关");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message);
            }
            finally
            {
                timer1.Interval = 1000 * 60 * 2;
                EndWaiting();
            }
        }

        private void riBtnCheckTime_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var dr = this.gridView1.GetFocusedDataRow();
            if (dr == null)
                return;
            ADSHalDataStruct.ADS_YMDHMS time = new ADSHalDataStruct.ADS_YMDHMS();
            time.year = (byte)(DateTime.Now.Year - 2000);
            time.month = (byte)DateTime.Now.Month;
            time.day = (byte)DateTime.Now.Day;
            time.hour = (byte)DateTime.Now.Hour;
            time.minute = (byte)DateTime.Now.Minute;
            time.sec = (byte)DateTime.Now.Second;

            m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
            m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
            m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));

            int iResult = ADSHalAPI.ADS_SetTime(ref Session._ADS_Comadapter, ref m_comm, ref time);
            ADSHelp.PromptResult(iResult, false);
        }

        private void riBtnOpenCloseDoor_ButtonPressed(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var cv = this.gridControl1.FocusedView as DevExpress.XtraGrid.Views.Card.CardView;
            if (cv == null)
                return;
            var dr = cv.GetFocusedDataRow();
            if (dr == null)
                return;

            var drMaster = this.gridView1.GetFocusedDataRow();
            m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));

            //m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            //m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            //m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));
            ADSHalDataStruct.ADS_LogicSubDeviceAddress subAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress();
            subAddress.physicalSubDevAddr = 0;
            subAddress.logicSubDevNumber = Convert.ToByte(dr["Physics_ID"].ToString());

            ADSHalDataStruct.ADS_IoInformation m_curIOInfo = new ADSHalDataStruct.ADS_IoInformation();
            m_curIOInfo.ioNumber = Convert.ToUInt32(dr["LSubDevice_Type"].ToString());
            m_curIOInfo.nIsAction = 1;

            //if (subAddress.logicSubDevNumber != 0 && m_curIOInfo.ioNumber != 0 && m_curIOInfo.nIsAction == 1)
            if (subAddress.logicSubDevNumber != 0 && m_curIOInfo.ioNumber != 0)
            {
                int iResult = 0;
                ADSHalDataStruct.ADS_IoAddress ioAddress = new ADSHalDataStruct.ADS_IoAddress();
                ioAddress.ioNumber = m_curIOInfo.ioNumber;
                if (e.Button.Caption == "开门")
                {
                    iResult = ADSHalAPI.ADS_OpenOputputIo(ref Session._ADS_Comadapter, ref m_comm, ref subAddress, ref ioAddress);
                }
                else
                {
                    iResult = ADSHalAPI.ADS_CloseOputputIo(ref Session._ADS_Comadapter, ref m_comm, ref subAddress, ref ioAddress);
                }
                //ADSHelp.PromptResult(iResult, false);
                if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                {
                    UI.ShowInfo(e.Button.Caption + "成功");
                }
                else
                {
                    UI.ShowError(e.Button.Caption + "失败");
                }
            }

        }
        public override void FormClose()
        {
            var dt = this.gridControl1.DataSource as DataTable;
            if (dt == null || dt.Rows.Count < 1)
            {
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                //// 连接
                m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
                m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
                m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));
                //Session._ADS_Comadapter.type = (byte)ADSHalConstant.ADS_COMAdapterType.ADS_ADT_TCP;
                int iResult = ADSHalAPI.ADS_DisconnectController(ref Session._ADS_Comadapter, ref m_comm);
                //ADSHelp.PromptResult(iResult, true); 
                //if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                //{

                //}
            }
            base.FormClose();
        }

        private void riBtnOpenTimeOut_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var btn = sender as ButtonEdit;
            if (btn == null)
                return;
            UInt32 t = 5;
            if (!UInt32.TryParse(btn.EditValue.ToString(), out t))
                return;
            if (t > 60)
            {
                UI.ShowError("门开超时报警时间不能超过60秒");
                return;
            }
            var cv = this.gridControl1.FocusedView as DevExpress.XtraGrid.Views.Card.CardView;
            if (cv == null)
                return;
            var dr = cv.GetFocusedDataRow();
            if (dr == null)
                return;

            var drMaster = this.gridView1.GetFocusedDataRow();
            m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));

            //m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            //m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            //m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));
            ADSHalDataStruct.ADS_LogicSubDeviceAddress subAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress();
            subAddress.physicalSubDevAddr = 0;
            subAddress.logicSubDevNumber = Convert.ToByte(dr["Physics_ID"].ToString());

            //ADSHalDataStruct.ADS_IoInformation m_curIOInfo = new ADSHalDataStruct.ADS_IoInformation();
            var LSubDevice_Type = Convert.ToByte(dr["LSubDevice_Type"].ToString());
            //m_curIOInfo.ioNumber = Convert.ToUInt32(dr["LSubDevice_Type"].ToString());
            //m_curIOInfo.nIsAction = 1;

            //if (subAddress.logicSubDevNumber != 0 && m_curIOInfo.ioNumber != 0 && m_curIOInfo.nIsAction == 1)
            if (subAddress.logicSubDevNumber == 0)
            {
                return;
            }
            var LogicSubDeviceConfiguration = new ADSHalDataStruct.ADS_LogicSubDeviceConfiguration();
            LogicSubDeviceConfiguration.logicSubDeviceType = LSubDevice_Type;
            LogicSubDeviceConfiguration.doorConfigurattion = new ADSHalDataStruct.ADS_DoorConfiguration();
            LogicSubDeviceConfiguration.doorConfigurattion.isEnableSuperPassword = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.superPassword = 12345678;
            LogicSubDeviceConfiguration.doorConfigurattion.openAlarmTime = t * 10;

            LogicSubDeviceConfiguration.doorConfigurattion.isCheckDoorSensor = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.readerType = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.workModeSwitchType = 0;
            var SubDevWorkMode = new ADSHalDataStruct.ADS_SubDevWorkMode();
            LogicSubDeviceConfiguration.doorConfigurattion.inWorkMode = SubDevWorkMode.outWorkMode;
            LogicSubDeviceConfiguration.doorConfigurattion.outWorkMode = SubDevWorkMode.outWorkMode;

            LogicSubDeviceConfiguration.doorConfigurattion.reserve1 = 0;
            LogicSubDeviceConfiguration.doorConfigurattion.reserve2 = 0;
            int iResult = ADSHalAPI.ADS_SetLogicSubDeviceConfiguration(ref Session._ADS_Comadapter, ref m_comm, ref subAddress, ref LogicSubDeviceConfiguration);
            //ADS_SetIoConfiguration
            var isOK = iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS;
            if (isOK)
            {
                isOK = new BAL.BAL_Device().SetSubDeviceOpenTime(dr["LSubDevice_ID"].ToString(), t);
                if (isOK)
                { UI.ShowInfo(e.Button.Caption + "成功"); }
                return;
            }
            dr["OpenTime"] = dr["OpenTime", DataRowVersion.Original];
            UI.ShowError(e.Button.Caption + "失败");
        }

        private void riBtnOpenTime_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var btn = sender as ButtonEdit;
            if (btn == null)
                return;
            UInt32 t = 5;
            if (!UInt32.TryParse(btn.EditValue.ToString(), out t))
                return;
            if (t > 10)
            {
                UI.ShowError("开门持续时间不能超过10秒");
                return;
            }
            var cv = this.gridControl1.FocusedView as DevExpress.XtraGrid.Views.Card.CardView;
            if (cv == null)
                return;
            var dr = cv.GetFocusedDataRow();
            if (dr == null)
                return;

            var drMaster = this.gridView1.GetFocusedDataRow();
            m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));

            //m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            //m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            //m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));
            ADSHalDataStruct.ADS_LogicSubDeviceAddress subAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress();
            subAddress.physicalSubDevAddr = 0;
            subAddress.logicSubDevNumber = Convert.ToByte(dr["Physics_ID"].ToString());

            //ADSHalDataStruct.ADS_IoInformation m_curIOInfo = new ADSHalDataStruct.ADS_IoInformation();
            var LSubDevice_Type = Convert.ToByte(dr["LSubDevice_Type"].ToString());
            //m_curIOInfo.ioNumber = Convert.ToUInt32(dr["LSubDevice_Type"].ToString());
            //m_curIOInfo.nIsAction = 1;

            //if (subAddress.logicSubDevNumber != 0 && m_curIOInfo.ioNumber != 0 && m_curIOInfo.nIsAction == 1)
            if (subAddress.logicSubDevNumber == 0)
            {
                return;
            }

            ADSHalDataStruct.ADS_IoAddress ioAddress = new ADSHalDataStruct.ADS_IoAddress();
            ioAddress.ioNumber = LSubDevice_Type;

            var IoConfiguration = new ADSHalDataStruct.ADS_IoConfiguration();
            IoConfiguration.normalLevel = 0;
            IoConfiguration.openTime = t * 10;
            IoConfiguration.functionType = Convert.ToByte(ADSHalConstant.ADS_IoFunctionType.ADS_IOFT_DEFAULT);
            IoConfiguration.checkType = Convert.ToByte(ADSHalConstant.ADS_IoCheckType.ADS_IOCT_2_STATE);
            IoConfiguration.isPermanenceArm = 1;

            IoConfiguration.isFastAlarm = 1;
            IoConfiguration.upperLimitValue = 100;
            IoConfiguration.lowerLimitValue = 0;

            IoConfiguration.reserve = 0;

            //public uint upperLimitValue;		///< 下溢告警值，只有检测类型设置为模拟，才会产生上下溢告警，端口实际
            /////< 采集的电压数值低于该值就产生下溢告警。只对具有AD输入的端口有意义。
            //public uint lowerLimitValue;		///< 上溢告警值，端口实际采集的电压数值高于该值就产生上溢告警。只对具有AD输入的端口有意义。 

            int iResult = ADSHalAPI.ADS_SetIoConfiguration(ref Session._ADS_Comadapter, ref m_comm, ref subAddress, ref ioAddress, ref IoConfiguration);
            //ADS_SetIoConfiguration
            var isOK = iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS;
            if (isOK)
            {
                isOK = new BAL.BAL_Device().SetSubDeviceOpenTimeOut(dr["LSubDevice_ID"].ToString(), t);
                if (isOK)
                { UI.ShowInfo(e.Button.Caption + "成功"); }
                return;
            }
            dr["OpenTimeOut"] = dr["OpenTimeOut", DataRowVersion.Original];
            UI.ShowError(e.Button.Caption + "失败");
        }

        private void barBtnSearch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var list = new List<string>();
            var dt = this.gridControl1.DataSource as DataTable;
            if (dt != null)
            {
                list = dt.AsEnumerable().Select(dr => dr["Physics_ID"].ToString()).ToList();
            }
            var f = new FormDeviceSearch(list);
            var res = f.ShowDialog();
            if (res == DialogResult.OK)
                FormRefresh();
        }

        private void riBtnFormatting_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                if (!UI.ShowOKCancelReturnBool("格式化设备后所有数据都需要同步,确定格式化吗?"))
                {
                    return;
                }
                StartWaiting();
                var dr = this.gridView1.GetFocusedDataRow();
                if (dr == null)
                    return;
                var isOk = new BAL.BAL_Device().ClearIsUpload();
                if (isOk)
                {
                    m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
                    m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
                    m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));

                    int iResult = ADSHalAPI.ADS_FormatController(ref Session._ADS_Comadapter, ref m_comm, 20000);
                    ADSHelp.PromptResult(iResult, false);
                }
                else
                {
                    UI.ShowError("格式化设备失败,请稍后重试.");
                    return;
                }
            }
            finally
            {
                EndWaiting();
            }
        }

        private void riBtnSubSettiong_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            var cv = this.gridControl1.FocusedView as DevExpress.XtraGrid.Views.Card.CardView;
            if (cv == null)
                return;
            var dr = cv.GetFocusedDataRow();
            if (dr == null)
                return;
            var drMaster = this.gridView1.GetFocusedDataRow();
            m_comm.deviceAddr = ADSHelp.IP2Int(drMaster["ComAdapter_Addr"].ToString());
            m_comm.devicePort = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_Port"].ToString()));
            m_comm.password = (ushort)(Convert.ToUInt16(drMaster["ComAdapter_pwd"].ToString()));
            var f = new FormDeveicSubEdit(dr["LSubDevice_ID"].ToString(), m_comm);
            if (f.ShowDialog() == DialogResult.OK)
            {
                var formMain = this.MdiParent as FormMain;
                if (formMain != null)
                    formMain.InitADS();
                FormRefresh();
            }

        }

    }
}
